<template>
  <div>
    <!-- 面包屑导航区 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>权限管理</el-breadcrumb-item>
      <el-breadcrumb-item>角色列表</el-breadcrumb-item>
    </el-breadcrumb>
    <!-- 卡片视图 -->
    <el-card>
      <el-row>
        <el-col>
          <el-button type="primary" @click="dialogVisible = true"
            >添加角色</el-button
          >
        </el-col>
      </el-row >
      <!-- 角色列表区域 -->
      <el-table :data="rolesList" border stripe>
        <!-- 展开列 -->
        <el-table-column type="expand">
          <template slot-scope="scope">
            <el-row :class="['dbbottom',index1==0? 'dbtop':'','vcenter']" v-for="item1,index1 in scope.row.children" :key="item1.id">
              <!-- 渲染一级权限 -->
              <el-col :span="5">
                <el-tag closable @close="removeRightById(scope.row,item1.id)">
                    {{item1.authName}}
                </el-tag>
                <i class="el-icon-caret-right"></i>
              </el-col>
              <!-- 渲染二、三级权限 -->
              <el-col :span="19">
                <!-- for循环嵌套渲染二级权限 -->
                <el-row :class="[index2===0?'':'dbtop','vcenter']" v-for="(item2,index2) in item1.children" :key="item2.id">
                  <el-col :span="6">
                    <el-tag type="success" closable @close="removeRightById(scope.row,item2.id)">
                      {{item2.authName}}
                    </el-tag>
                  <i class="el-icon-caret-right"></i>
                  </el-col>
                  <el-col :span="18">
                    <el-tag type="warning" v-for="item3 in item2.children" :key="item3.id" closable @close="removeRightById(scope.row,item3.id)">
                      {{item3.authName}}
                    </el-tag>
                  </el-col>
                </el-row>
              </el-col>
            </el-row>
          </template>
        </el-table-column>
        <!-- 索引列 -->
        <el-table-column type="index" label="序号"></el-table-column>
        <el-table-column prop="roleName" label="角色名称"> </el-table-column>
        <el-table-column prop="roleDesc" label="角色描述"> </el-table-column>
        <el-table-column label="权限等级">
          <!-- 作用域插槽  -->
          <template slot-scope="scope">
            <el-button type="primary" icon="el-icon-edit" @click="showEditDialog(scope.row.id)">编辑</el-button>
            <el-button type="danger" icon="el-icon-delete" @click="removeRolesById(scope.row.id)">删除</el-button>
            <el-button type="warning" icon="el-icon-setting"
              @click="showSetRightDialog(scope.row)" >分配权限</el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-card>
    <!-- 添加角色的对话框 -->
    <el-dialog
      title="添加角色"
      :visible.sync="dialogVisible"
      width="50%"
      @close="addDialogClosed"
    >
      <!-- 内容主体区域 -->
      <el-form
        :model="addForm"
        :rules="RolesFromRules"
        ref="addFormRef"
        label-width="100px"
      >
        <el-form-item label="角色名称" prop="roleName">
          <el-input v-model="addForm.roleName"></el-input>
        </el-form-item>
        <el-form-item label="角色描述" prop="roleDesc">
          <el-input v-model="addForm.roleDesc"></el-input>
        </el-form-item>
      </el-form>
      <!-- 底部按钮区域 -->
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="addRoles"> 确 定 </el-button>
      </span>
    </el-dialog>
    <!-- 修改角色的对话框 -->
    <el-dialog
      title="修改角色"
      :visible.sync="EditdialogVisible"
      width="50%"
      @close="editDialogClosed">
      <!-- 内容主体区域 -->
      <el-form
        :model="editForm"
        :rules="RolesFromRules"
        ref="editFormRef"
        label-width="100px">
        <el-form-item label="角色名称" prop="roleName">
          <el-input v-model="editForm.roleName"></el-input>
        </el-form-item>
        <el-form-item label="角色描述" prop="roleDesc">
          <el-input v-model="editForm.roleDesc"></el-input>
        </el-form-item>
      </el-form>
      <!-- 底部按钮区域 -->
      <span slot="footer" class="dialog-footer">
        <el-button @click="EditdialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="editRoles"> 确 定 </el-button>
      </span>
    </el-dialog>
    <!-- 分配权限的对话框 -->
    <el-dialog title="分配权限" :visible.sync="setRightsdialogVisible"
    width="50%" @close='setRightsDialogClose'>
    <!--树形控件  data为数据来源  props为数据绑定的字段-->
      <el-tree :data="rightsList" :props="treeProps" show-checkbox
       node-key='id' default-expand-all :default-checked-keys='defKeys' ref="treeRef"></el-tree>
      <span slot="footer" class="dialog-footer">
    <el-button @click="setRightsdialogVisible = false">取 消</el-button>
    <el-button type="primary" @click="allotRights">确 定</el-button>
  </span>
</el-dialog>
  </div>
</template>

<script>
export default {
  data() {
    return {
      rolesList: [],
      //添加角色的表单数据对象
      addForm: {},
      //添加角色的对话框显示与隐藏
      dialogVisible: false,
      //修改角色的表单数据对象
      editForm:{},
      //修改角色的对话框显示与隐藏
      EditdialogVisible:false,
      //角色权限的数据
      rightsList:[],
      //分配角色权限的对话框显示与隐藏
      setRightsdialogVisible:false,
      //树形控件的属性绑定对象
      treeProps:{
        label:'authName',
        children:'children'
      },
      //默认选中的节点id值数组
      defKeys:[],
      //当前即将分配权限的id
      roleId:'',
      //添加和修改角色表单的验证规则
      RolesFromRules: {
        roleName: [
          { required: true, message: "请输入角色名", trigger: "blur" },
          {
            min: 2,
            max: 8,
            message: "角色名的长度在 2 到 8 个字符",
            trigger: "blur",
          },
        ],
        roleDesc: [
          { required: true, message: "请输入角色描述", trigger: "blur" },
          {
            min: 2,
            max: 10,
            message: "密码的长度在 2 到 10 个字符",
            trigger: "blur",
          },
        ],
      },
    };
  },
  created() {
    this.getRolesList();
  },
  methods: {
    async getRolesList() {
      const { data: res } = await this.$http.get("roles");
      if (res.meta.status !== 200) {
        return this.$message.error("获取角色列表失败！");
      }
      this.rolesList = res.data;
    },
    //监听添加对话框关闭 重置器表单
    addDialogClosed() {
      this.$refs.addFormRef.resetFields();
    },
    //添加角色
    addRoles() {
      this.$refs.addFormRef.validate(async (valid) => {
        if (!valid) {
          return;
        }
        const { data: res } = await this.$http.post("roles", this.addForm);
        if (res.meta.status !== 201) {
          this.$message.error("添加角色失败");
        }
        this.$message.success("添加角色成功");
        //隐藏添加对话框
        this.dialogVisible = false;
        //刷新列表
        this.getRolesList();
      });
    },
    //先查询角色 再进行修改
    async showEditDialog(id){
      const {data:res}= await this.$http.get('roles/'+id)
      if(res.meta.status!==200){
        return this.$message.error('查询角色信息失败')
      }
      this.editForm=res.data
      this.EditdialogVisible=true
    },
     //监听添加对话框关闭 重置器表单
    editDialogClosed() {
      this.$refs.editFormRef.resetFields();
    },
    //编辑角色
    editRoles() {
      this.$refs.editFormRef.validate(async (valid) => {
        // console.log(valid);
        if (!valid) {
          return;
        }
        const { data: res } = await this.$http.put("roles/"+this.editForm.roleId,{roleName: this.editForm.roleName,roleDesc: this.editForm.roleDesc});
        if (res.meta.status !== 200) {
          this.$message.error("修改角色失败");
        }
        this.$message.success("修改角色成功");
        //隐藏添加对话框
        this.EditdialogVisible = false;
        //刷新列表
        this.getRolesList();
      });
    },
    //根据id删除角色
    async removeRolesById(id){
      //弹框提示是否删除
      const confirmResult= await this.$confirm('此操作将永久删除该角色, 是否继续?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning',
      }).catch(err=>err)
    //如果用户确认删除，返回为字符串comfirm
    //如果用户取消删除，返回字符串cancel
    if(confirmResult!=='confirm'){
        return this.$message.info('已取消删除')
    }
    const {data:res}= await this.$http.delete('roles/'+id)
      if(res.meta.status!==200){
      return this.$message.error('删除角色失败')
    }
    this.$message.success('删除角色成功')
    //刷新列表
    this.getRolesList();
    },
    //根据id删除对应权限
    async removeRightById(role,rightId){
       //弹框提示是否删除
      const confirmResult= await this.$confirm('此操作将永久删除该权限, 是否继续?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning',
    }).catch(err=>err)
    //如果用户确认删除，返回为字符串comfirm
    //如果用户取消删除，返回字符串cancel
    if(confirmResult!=='confirm'){
        return this.$message.info('已取消删除')
    }
    const {data:res}= await this.$http.delete(`roles/${role.id}/rights/${rightId}`)
    if(res.meta.status!==200){
      return this.$message.error('删除权限失败')
    }
    this.$message.success('删除权限成功')
    // this.getRolesList();
    role.children=res.data
    },
    async showSetRightDialog(role){
      this.roleId=role.id
        const {data:res}= await this.$http.get('rights/tree')
        if(res.meta.status!==200){
          return this.$message.error('获取权限数据失败')
        }
        //获取到的权限数据保存到data中
        this.rightsList=res.data
        //递归获取三级节点
        this.getdefKeys(role,this.defKeys)
        this.setRightsdialogVisible=true
    },
    //通过递归获取到角色下所有三级权限的id
    getdefKeys(node,arr){
      //判断是否有三级节点
      if(!node.children){
        return arr.push(node.id)
      }
      node.children.forEach(item=>{
        this.getdefKeys(item,arr)
      })
    },
    //监听对话框分配权限关闭事件
    setRightsDialogClose(){
      this.defKeys=[];
    },
    //点击为角色添加权限
    async allotRights(){
      const keys=[
        ...this.$refs.treeRef.getCheckedKeys(),
        ...this.$refs.treeRef.getHalfCheckedKeys()
      ]
      console.log(keys)
      const idStr=keys.join(',')
      const{data:res} =await this.$http.post(`roles/${this.roleId}/rights`,{rids:idStr})
      if(res.meta.status!==200){
        return this.$message.error('分配权限失败')
      }
      this.$message.success('分配权限成功')
      this.getRolesList()
      this.setRightsdialogVisible=false
    }
  }
};
</script>

<style lang="less" scoped>
  .el-tag{
    margin: 10px;
  }
  .dbtop{
    border-top: 1px solid gainsboro;
  }
  .dbbottom{
      border-bottom: 1px solid gainsboro;
  }
  .vcenter{
    display: flex;
    align-items: center;
  }
</style>